package com.openatc.agent.controller;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.openatc.agent.gateway.WebSocketServer;
import com.openatc.agent.model.*;
import com.openatc.agent.service.*;
import com.openatc.agent.service.impl.VipRouteOperationRecordExtractor;
import com.openatc.agent.service.impl.WebOperationCollector;
import com.openatc.agent.service.impl.WebOperationRecordExtractor;
import com.openatc.agent.utils.RedisTemplateUtil;
import com.openatc.comm.common.CosntDataDefine;
import com.openatc.comm.data.MessageData;
import com.openatc.core.common.IErrorEnumImplOuter;
import com.openatc.core.model.InnerError;
import com.openatc.core.model.RESTRet;
import com.openatc.core.model.RESTRetBase;
import com.openatc.core.util.DateUtil;
import com.openatc.core.util.RESTRetUtils;
import com.openatc.extend.common.aop.model.SysLog;
import com.openatc.model.model.ControlPattern;
import com.openatc.model.model.MyGeometry;
import com.openatc.model.model.StatusPattern;
import com.openatc.model.model.SystemEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.text.ParseException;
import java.util.*;

import static com.openatc.core.common.IErrorEnumImplOuter.*;
import static com.openatc.model.model.SystemEvent.EVENT_LEVEL_NORMAL;
import static com.openatc.model.model.SystemEvent.TYPE_SYSTEM;

@Slf4j
@RestController
public class VipRouteController {

    @Autowired
    VipRouteDao vipRouteDao;
    @Autowired
    public RedisTemplateUtil redisTemplate;
    @Autowired
    VipRouteDeviceDao vipRouteDeviceDao;

    @Autowired
    private MessageService messageService;

    @Autowired
    VipRouteExecuteDao vipRouteExecuteDao;
    @Autowired
    private WebSocketServer webSocketServer;

    private String agenttype = "asc";
    private static final String ASC_VIPROUTE_STATUS = "asc:viproute/status:";
    private static final String ZEROSECONDS = "00:00";
    private static final Map<Integer, Integer> vipRouteSystemEvent = new HashMap<>();
    private Sort.Order order = Sort.Order.asc("id");
    private Sort sort = Sort.by(order);
    private Gson gson = new Gson();

    // 获取所有的勤务路线的全部信息
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    @GetMapping(value = "/viproute")
    public RESTRetBase getVipRoute() throws ParseException {
        List<VipRoute> vipRoutes = vipRouteDao.findAll(sort);

        for (VipRoute vipRoute : vipRoutes) {
            List<VipRouteDevice> vipRouteDeviceList = vipRouteDeviceDao.findByViprouteidWithGeo(vipRoute.getId());
            vipRoute.setDevs(vipRouteDeviceList);
            addGeometryToVipRoute(vipRoute);
        }

        return RESTRetUtils.successObj(vipRoutes);
    }

    // 获取所有的勤务路线的全部信息
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    @GetMapping(value = "/viproute/type/{type}/search/{condition}")
    public RESTRetBase getVipRouteByCondition(@PathVariable int type, @PathVariable String condition)   {
        if(condition.equals("*"))
            condition = "";
        List<VipRoute> vipRoutes = vipRouteDao.findVipRouteByCondition(type,condition);

        for (VipRoute vipRoute : vipRoutes) {
            // 放入路口信息
            List<VipRouteDevice> vipRouteDeviceList = vipRouteDeviceDao.findByViprouteidWithGeo(vipRoute.getId());
            vipRoute.setDevs(vipRouteDeviceList);
            addGeometryToVipRoute(vipRoute);

            // 判断任务是否执行中
            if (vipRouteExecuteDao.containsRoute(vipRoute.getId())) {
                vipRoute.setState(1);
            }else{
                int schedule = vipRoute.getSchedule();
                // 自动
                if (schedule == 1) {
                    vipRoute.setState(2);
                }
                // 手动
                else {
                    vipRoute.setState(0);
                }
            }

        }

        return RESTRetUtils.successObj(vipRoutes);
    }

    // 获取单个勤务路线的全部信息
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    @GetMapping(value = "/viproute/{id}")
    public RESTRetBase getVipRouteById(@PathVariable int id) {
        VipRoute vipRoute = vipRouteDao.findById(id);
        List<VipRouteDevice> vipRouteDeviceList = vipRouteDeviceDao.findByViprouteidWithGeo(vipRoute.getId());
        vipRoute.setDevs(vipRouteDeviceList);
        addGeometryToVipRoute(vipRoute);

        List<VipRouteDeviceStatus> stateLists = this.getVipRouteStatusList(id);
        for (VipRouteDevice device : vipRoute.getDevs()) {
            for(VipRouteDeviceStatus stateList : stateLists ){
                if (device.getAgentid().equals(stateList.getAgentid())){
                    device.setState(stateList.getState());
                    device.setResttime(stateList.getResttime());
                    device.setCurrentControl(stateList.getControl());
                    device.setStateName(stateList.getStateName());
                }
            }
        }

        // 判断任务是否执行中
        if (vipRouteExecuteDao.containsRoute(vipRoute.getId())) {
            vipRoute.setState(1);
        }else{
            vipRoute.setState(0);
        }

        return RESTRetUtils.successObj(vipRoute);
    }


    private void addGeometryToVipRoute(VipRoute vipRoute)  {
        List<VipRouteDevice> vipRouteDevs = vipRoute.getDevs();
        if(vipRouteDevs == null){
            return;
        }
        for (VipRouteDevice vipRouteDev : vipRouteDevs) {
            vipRouteDev.setGeometry(gson.fromJson(vipRouteDev.getGeometryStr(), MyGeometry.class));
            vipRouteDev.setGeometryStr("");
        }
    }


    // 查询所有勤务路线的简略信息
    @GetMapping(value = "/viproute/simple")
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    public RESTRetBase getVipRouteByName() {
        List<VipRoute> vipRoutes = vipRouteDao.getSimpleInfoForVipRoute();
        for (VipRoute vipRoute : vipRoutes) {
            addGeometryToVipRoute(vipRoute);
        }
        return RESTRetUtils.successObj(vipRoutes);
    }

    // 新增勤务路线
    @RequiresPermissions("openatc:interrupt:vip")
    @PostMapping(value = "/viproute")
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    public RESTRetBase addVipRoutes(@RequestBody VipRoute routeEntity) throws ParseException {
        VipRoute hasNoDevsRoute = new VipRoute();
        hasNoDevsRoute.setName(routeEntity.getName());
        VipRoute r = vipRouteDao.findByName(routeEntity.getName());
        //校验路线名称是否重复
        if (r != null) {
            return RESTRetUtils.errorObj(E_6001);
        }
        VipRoute dbRoute = vipRouteDao.save(hasNoDevsRoute);
        // 拿到id后更新
        int dbRouteId = dbRoute.getId();
        routeEntity.setId(dbRouteId);
        return updateVipRoute(routeEntity);
    }

    // 更新勤务路线
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    @RequiresPermissions("openatc:interrupt:vip")
    @PutMapping(value = "/viproute")
    @Transactional
    @Modifying
    @SysLog(collector = WebOperationCollector.class,extractor = VipRouteOperationRecordExtractor.class)
    public RESTRetBase updateVipRoute(@RequestBody VipRoute routeEntity) {
        if (!StringUtils.hasLength(routeEntity.getName())) {
               return RESTRetUtils.errorObj(E_0007);
        }
        int id = routeEntity.getId();
        // 新增
        if (id == 0) {
            VipRoute r = vipRouteDao.findByNameAndType(routeEntity.getName(), routeEntity.getType());
            //校验路线名称是否重复
            if (r != null) {
                // 类型不同的路线，路线名称可以重复
                return RESTRetUtils.errorObj(E_6001);
            }
        }
        // 更新
        else {
            VipRoute dbVipRoute = vipRouteDao.findById(id);
            if (!routeEntity.getName().equals(dbVipRoute.getName())) {
                VipRoute r = vipRouteDao.findByNameAndType(routeEntity.getName(), routeEntity.getType());
                // 校验路线名称是否重复
                if (r != null) {
                    // 类型不同的路线，路线名称可以重复
                    return RESTRetUtils.errorObj(E_6001);
                }
            }
        }
        // 0 执行前先判断一下是否存在执行中的设备，如果存在，应答错误
        List<VipRouteDevice> vipRouteDevices = vipRouteDeviceDao.findByViprouteid(id);
        for (VipRouteDevice vipRouteDevice : vipRouteDevices) {
            VipRouteDeviceStatus vipRouteDeviceStatus = vipRouteExecuteDao.getStatusByRouteidAndAgentid(id, vipRouteDevice.getAgentid());
            if (vipRouteDeviceStatus == null) continue;
            if (vipRouteDeviceStatus.getState() == 1) return RESTRetUtils.errorObj(E_6002);
        }
        // 1 首先删除这条路线之前的设备
        vipRouteDeviceDao.deleteByViprouteid(id);

        // 2 保存到数据库中
        VipRoute dbRoute = vipRouteDao.save(routeEntity);

        List<VipRouteDevice> vipRouteDeviceList = routeEntity.getDevs();
        if (vipRouteDeviceList != null && vipRouteDeviceList.size() > 0) {
            for (VipRouteDevice vipRouteDevice : vipRouteDeviceList) {
                vipRouteDevice.setViprouteid(dbRoute.getId());
                vipRouteDeviceDao.save(vipRouteDevice);
            }
        }

        // 3 应答请求
        addGeometryToVipRoute(dbRoute);
        return RESTRetUtils.successObj(dbRoute);
    }

    // 更新勤务路线名称
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    @RequiresPermissions("openatc:interrupt:vip")
    @PutMapping(value = "/viproute/name")
    public RESTRetBase updateVipRouteName(@RequestBody VipRoute routeEntity) {
        int id = routeEntity.getId();
        VipRoute route = vipRouteDao.findById(id);
        route.setName(routeEntity.getName());
        try {
            vipRouteDao.save(route);
        } catch (Exception e) {
            return RESTRetUtils.errorObj(E_5001);
        }
        return RESTRetUtils.successObj(route);
    }

    //删除勤务路线
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    @RequiresPermissions("openatc:interrupt:vip")
    @DeleteMapping(value = "/viproute/{id}")
    @SysLog(collector = WebOperationCollector.class,extractor = VipRouteOperationRecordExtractor.class)
    public RESTRetBase deleteVipRoute(@PathVariable int id) {
        // check state
        // 获取路线状态
        int routeState = 0;
        List<VipRouteDeviceStatus> vriss = getVipRouteStatusList(id);
        for (VipRouteDeviceStatus dev : vriss) {
            int state = dev.getState();
            if (state > 0) {
                routeState = state;
            }
        }
        if (routeState == 1) {
            return RESTRetUtils.errorObj(IErrorEnumImplOuter.E_6002);
        }
        List<VipRouteDevice> vipRouteDevices = vipRouteDeviceDao.findByViprouteid(id);
        if (vipRouteDevices != null && vipRouteDevices.size() > 0) {
            for (VipRouteDevice vipRouteDevice : vipRouteDevices) {
                vipRouteDeviceDao.deleteById(vipRouteDevice.getId());
            }
        }
        vipRouteDao.deleteById(id);
        return RESTRetUtils.successObj();
    }

    // 后台自动调度和启动定时器，每分钟判断一次
    @Scheduled(cron = "0 0/1 * * * ?")
    public void autoExecuteVipRoutes(){
        log.warn("Auto Execute VipRoutes Start!");
        List<VipRoute> vipRoutes = vipRouteDao.findAll(sort);
        Calendar calendar = new GregorianCalendar();
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int weekday = calendar.get(Calendar.DAY_OF_WEEK)-1; // 1=周日
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        for( VipRoute vipRoute :  vipRoutes){
            try{
                if( vipRoute.getStarttime() == null || vipRoute.getEndtime() == null)
                    continue;

                String[] start = vipRoute.getStarttime().split(":");
//                String[] end = vipRoute.getEndtime().split(":");

                int vipRouteStartHour = Integer.parseInt(start[0]);
                int vipRouteStartMinute = Integer.parseInt(start[1]);


                int viprouteid = vipRoute.getId();

                // 调度类型：0-手动，1-自动
                if(vipRoute.getSchedule() == 1){
                    if( ! dateExist( vipRoute.getMonth(), month )  )
                        continue;
                    if( ! dateExist( vipRoute.getDate(), day )  )
                        continue;
                    if( ! dateExist( vipRoute.getDay(), weekday )  )
                        continue;

                    // 到达任务启动时间
                    if( hour == vipRouteStartHour && minute == vipRouteStartMinute ){
                        log.warn("Auto Execute VipRoutes Scheduled:" + vipRoute);
                        // 发送调度到达执行时间
                        sendScheduleStartSystemEvent(vipRoute.getName());
                        vipRouteSystemEvent.put(viprouteid,0);

                        List<VipRouteDeviceStatus> stateLists = this.getVipRouteStatusList(vipRoute.getId());
                        for( VipRouteDeviceStatus routeDeviceStatus : stateLists ){
                            if( routeDeviceStatus.getStateName() != null && routeDeviceStatus.getStateName().equals("UP") ){
                                VipRouteExecute vipRouteExecute = new VipRouteExecute(viprouteid,routeDeviceStatus.getAgentid(),1 );
                                executeVipRoutes(vipRouteExecute);
                            }
                        }
                    }
                }
            }catch (Exception e){
                log.warn(e.getMessage());
            }
        }
    }

    /**
     * 发送调度任务开始通知
     * @param name
     */
    private void sendScheduleStartSystemEvent(String name) {
        sendSystemEvent(name,1);
    }

    /**
     * 发送调度任务结束通知
     * @param name
     */
    private void sendScheduleEndSystemEvent(String name) {
        sendSystemEvent(name,0);
    }
    /**
     * 发送调度任务到达执行时间
     * @param name
     * @Param startOrEnd 0-结束，1-开始
     */
    private void sendSystemEvent(String name,int startOrEnd) {
        SystemEvent systemEvent = new SystemEvent();

        systemEvent.setType(TYPE_SYSTEM);
        systemEvent.setLevel(EVENT_LEVEL_NORMAL);
        systemEvent.setSource("来自系统的通知");
        String content;
        if (startOrEnd == 0) {
            content = "特勤路线 " + name + " 到达调度结束时间,结束自动执行。";
        } else {
            content = "特勤路线 " + name + " 到达调度开始时间,开始自动执行。";
        }
        systemEvent.setContent(content);
        systemEvent.setCreatetime(DateUtil.date2str(new Date()));
        webSocketServer.sendSystemEvent(systemEvent);
    }

    private boolean dateExist(int[] arrays, int value) {
        if(arrays == null)
            return true;
        if(arrays.length == 0)
            return true;

        for(int a : arrays){
            if( a == value )
                return true;
        }
        return false;
    }

    //执行勤务路线
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    @RequiresPermissions("openatc:interrupt:vip")
    @PostMapping(value = "/viproute/execute")
    @SysLog(collector = WebOperationCollector.class,extractor = VipRouteOperationRecordExtractor.class)
    public RESTRetBase executeVipRoutes(@RequestBody VipRouteExecute vipRouteExecute) {
        int viprouteid = vipRouteExecute.getViprouteid();
        String agentid = vipRouteExecute.getAgentid();
        int operation = vipRouteExecute.getOperation();
        // 0 根据前端传过来的数据找到数据库中的vip路线设备
        VipRouteDevice vrDevice = vipRouteDeviceDao.findByViprouteidAndAgentid(viprouteid, agentid);
        // 1 将控制方式等发送给信号机
        JsonElement data = gson.toJsonTree(vrDevice.getData());
        MessageData messageData = new MessageData(agentid, CosntDataDefine.setrequest, CosntDataDefine.ControlPattern, data);

        // 执行勤务路线
        if (operation == 1) {
            if (vipRouteExecuteDao.contains(agentid))
                return RESTRetUtils.errorObj(E_6002);

            RESTRet restRet = messageService.postDevsMessage(messageData);
            // 应答错误处理
            if (restRet.getData() instanceof InnerError) {
                log.warn("viproute execute error:" + restRet.getCode() + " - " + restRet.getMessage());
                return restRet;
            } else {
                messageData = (MessageData) restRet.getData();
                JsonElement succeess = messageData.getData().getAsJsonObject().get("success");
                if(succeess == null || succeess.getAsInt() != 0){
                    log.warn("viproute execute error:" + restRet.getCode() + " - " + restRet.getMessage());
                    return restRet;
                }
            }
            // 加入任务缓存，后台计算剩余时间
            ControlPattern controlPattern = vrDevice.getData();
            int totaltime = controlPattern.getDuration();

            if(controlPattern.getData() != null){
                JsonElement dataElement = gson.toJsonTree(controlPattern.getData());
                JsonObject controlPatternData = dataElement.getAsJsonObject();
                if (controlPatternData.has("duration")) {
                    totaltime = controlPatternData.get("duration").getAsInt();
                }
            }

            vipRouteExecute.setTotaltime(totaltime);
            vipRouteExecute.setStatus(new VipRouteDeviceStatus(agentid, 1, ""));
            vipRouteExecuteDao.add(vipRouteExecute);
            log.warn("viproute execute pattern success:" + vipRouteExecute);

        }
        // 取消勤务路线
        else if (operation == 0) {
            // 回自主控制
            RESTRet restRet = backSelfControl(agentid);
            vipRouteExecuteDao.remove(agentid);

            if (restRet.getData() instanceof InnerError)
                return restRet;
            log.warn("viproute execute recover success:" + vipRouteExecute);

        }
        return RESTRetUtils.successObj();
    }

    private RESTRet backSelfControl(String agentid) {
        JsonObject selfControl = new JsonObject();
        selfControl.addProperty("control", 0);
        MessageData selfMessage = new MessageData(agentid, CosntDataDefine.setrequest, CosntDataDefine.ControlPattern, selfControl);
        return messageService.postDevsMessage(selfMessage);
    }

    // 后台计算剩余时间和恢复控制
    @Scheduled(fixedRate = 1000)
    public void vipRouteexecuteThread(){

        for(  VipRouteExecute vipRouteExecute : vipRouteExecuteDao.onExcuteDevlist ) {
            try {
                int totaltime = vipRouteExecute.getTotaltime();
                String agentid = vipRouteExecute.getAgentid();
                int viprouteid = vipRouteExecute.getViprouteid();



                // 将时间更新到redis中
                if (totaltime > 0) {
                    totaltime -=1;
                    vipRouteExecute.setTotaltime(totaltime);

                    //相位用两位字符串表示，不足位数补0
                    String hour = String.format("%2d", totaltime / 3600).replace(" ", "0");
                    String min = String.format("%2d", totaltime / 60 % 60).replace(" ", "0");
                    String sec = String.format("%2d", totaltime % 60).replace(" ", "0");
                    String resttime = hour + ":" + min + ":" + sec;
                    VipRouteDeviceStatus vipRouteDeviceStatus = vipRouteExecute.getStatus();
                    vipRouteDeviceStatus.setResttime(resttime);
                } else { // 回自主控制
                    VipRouteDeviceStatus vipRouteDeviceStatus = vipRouteExecute.getStatus();
                    int operation = vipRouteExecute.getOperation();

                    if( operation == 1 ){ // 执行中
                        vipRouteExecute.setOperation(0);
                        // 判断当前控制是否是对应的特勤控制，若不是则应答失败
                        VipRouteDevice vrDevice = vipRouteDeviceDao.findByViprouteidAndAgentid(viprouteid, agentid);
                        int vipRouteControl = vrDevice.getData().getControl();
                        // 获取当前控制方案
                        MessageData messageDataStatusPattern = redisTemplate.getStatusPatternMessageDadaFromRedis(agentid);
                        if( messageDataStatusPattern != null){
                            StatusPattern statusPattern = gson.fromJson(messageDataStatusPattern.getData(),StatusPattern.class);
                            if(statusPattern != null){
                                int currentControl = statusPattern.getControl();
                                // 方案已改变，不自动取消
                                if(vipRouteControl != currentControl){
                                    String resttime = "Pattern Changed";
                                    vipRouteDeviceStatus.setResttime(resttime);
                                    log.info( "Auto Recover VipRoutes Cancel by pattern is change ! agentid:" + agentid + "vipRouteControl:" + vipRouteControl + " currentControl:" + currentControl );
                                }else{
                                    backSelfControl(agentid);
                                    log.info( "Auto Recover VipRoutes succeed by time end! ! agentid:" + agentid + "vipRouteControl:" + vipRouteControl + " currentControl:" + currentControl );
                                }
                            }
                        }
                        vipRouteExecuteDao.remove(agentid);
                    }else{ // 执行时间已到达但未成功恢复

                    }
                    if (vipRouteSystemEvent.get(viprouteid) == null || vipRouteSystemEvent.get(viprouteid) == 0) {
                        VipRoute virRoute = vipRouteDao.findById(viprouteid);
                        sendScheduleEndSystemEvent(virRoute.getName());
                        vipRouteSystemEvent.put(viprouteid,1);
                    }
                }
            } catch (Exception e) {
                log.warn("Vip road thread interrupted!error:" + e.getMessage() + " agentid:" + vipRouteExecute.getAgentid());
                break;
            }
        }

    }

    // 查询勤务路线路口状态
//    @RequiresRoles(value = {"admin","superadmin"},logical = Logical.OR)
    @GetMapping(value = "/viproute/{id}/status")
    public RESTRetBase getVipRouteStatus(@PathVariable int id) {

        // 获取路线状态
        List<VipRouteDeviceStatus> vriss = getVipRouteStatusList(id);
        return RESTRetUtils.successObj(vriss);
    }

    /**
     * @Author: yangyi
     * @Date: 2022/1/5 17:45
     * @Description: get vip route detail
     */
    public List<VipRouteDeviceStatus> getVipRouteStatusList(int id) {
        List<VipRouteDeviceStatus> vriss = new ArrayList<>();

        // 查询路线中的路口信息，并修改状态
        List<VipRouteDeviceOnline> VipRouteDevices =  vipRouteDao.findVipRouteWithDevStateById(id);
        for (VipRouteDeviceOnline vipRouteDeviceOnline : VipRouteDevices) {

            VipRouteDeviceStatus vipRouteDeviceStatus = vipRouteExecuteDao.getStatusByRouteidAndAgentid(id,vipRouteDeviceOnline.getAgentid());
            // 当前控制中不存在，则创建一个
            if(vipRouteDeviceStatus == null)
                vipRouteDeviceStatus = new VipRouteDeviceStatus(vipRouteDeviceOnline.getAgentid(), 0, "00:00");

            vriss.add(vipRouteDeviceStatus);
        }


        for(VipRouteDeviceOnline vipRouteDeviceOnline : VipRouteDevices){
            String agentid = vipRouteDeviceOnline.getAgentid();
            VipRouteDeviceStatus vipRouteDeviceStatus = GetVipRouteDeviceStatusbyID(vriss, agentid);
            String online = vipRouteDeviceOnline.getState();
            vipRouteDeviceStatus.setStateName(online);
            if(online.equals("DOWN")) {
                vipRouteDeviceStatus.setControl(-1);
                continue;
            }
            MessageData messageData = redisTemplate.getStatusPatternMessageDadaFromRedis(agentid);
            if( messageData == null){
                vipRouteDeviceStatus.setControl(-1);
                continue;
            }
            StatusPattern statusPattern = gson.fromJson(messageData.getData().getAsJsonObject(),StatusPattern.class);
            if(statusPattern == null){ // 无法获取到方案状态，设备不在线
                vipRouteDeviceStatus.setControl(-1);
            } else{ // 设备在线,设置设备当前状态
                int curControl = statusPattern.getControl();
                vipRouteDeviceStatus.setControl(curControl);
            }
        }
        return vriss;
    }

    /**
     * 根据路口ID，从vip路线中，获取路口的状态
     * @author: zhangwenchao
     * @param agentid
     * @return 单个路口的状态
     */
    private VipRouteDeviceStatus GetVipRouteDeviceStatusbyID(List<VipRouteDeviceStatus> vriss ,String agentid){
        VipRouteDeviceStatus vipRouteDeviceStatus = null;
        for(VipRouteDeviceStatus deviceStatus: vriss ){
            if(deviceStatus.getAgentid().equals(agentid)){
                vipRouteDeviceStatus = deviceStatus;
                break;
            }
        }
        return vipRouteDeviceStatus;

    }
}
